package com.aspire.aimini.controller;


import com.aspire.aimini.model.entity.ExportTask;
import com.aspire.aimini.service.ExportService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;


import java.util.List;
import java.util.Map;

/**
 * 导出服务控制器
 *
 * @author wangguiyou
 * @date 2024-12-19
 */
@Slf4j
@RestController
@RequestMapping("/api/export")
@RequiredArgsConstructor
@Tag(name = "导出服务", description = "导出服务相关的API接口")
public class ExportController {

    private final ExportService exportService;

    /**
     * 创建导出任务
     *
     * @param request 导出请求
     * @param userId  用户ID
     * @return 导出任务
     */
    @PostMapping("/task")
    @Operation(summary = "创建导出任务", description = "创建新的导出任务")
    public ResponseEntity<ExportTask> createExportTask(
            @Valid @RequestBody Map<String, Object> request,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("创建导出任务: userId={}", userId);

        String dataType = (String) request.get("dataType");
        String format = (String) request.get("format");
        @SuppressWarnings("unchecked")
        Map<String, Object> filters = (Map<String, Object>) request.get("filters");
        @SuppressWarnings("unchecked")
        Map<String, Object> options = (Map<String, Object>) request.get("options");

        ExportTask task = exportService.createExportTask(dataType, format, filters, options, userId);
        return ResponseEntity.ok(task);
    }

    /**
     * 查询导出任务
     *
     * @param userId   用户ID
     * @param status   任务状态
     * @param dataType 数据类型
     * @param pageable 分页参数
     * @return 导出任务分页列表
     */
    @GetMapping("/task")
    @Operation(summary = "查询导出任务", description = "分页查询导出任务列表")
    public ResponseEntity<Page<ExportTask>> getExportTasks(
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId,
            @Parameter(description = "任务状态") @RequestParam(required = false) String status,
            @Parameter(description = "数据类型") @RequestParam(required = false) String dataType,
            Pageable pageable) {
        log.info("查询导出任务: userId={}, status={}, dataType={}", userId, status, dataType);

        Page<ExportTask> tasks = exportService.getExportTasks(userId, status, dataType, pageable);
        return ResponseEntity.ok(tasks);
    }

    /**
     * 根据ID获取导出任务
     *
     * @param taskId 任务ID
     * @param userId 用户ID
     * @return 导出任务
     */
    @GetMapping("/task/{taskId}")
    @Operation(summary = "根据ID获取导出任务", description = "根据ID获取导出任务详情")
    public ResponseEntity<ExportTask> getExportTaskById(
            @Parameter(description = "任务ID") @PathVariable String taskId,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("根据ID获取导出任务: taskId={}, userId={}", taskId, userId);

        ExportTask task = exportService.getExportTaskById(taskId);
        return ResponseEntity.ok(task);
    }

    /**
     * 获取导出任务下载链接
     *
     * @param taskId 任务ID
     * @param userId 用户ID
     * @return 下载链接
     */
    @GetMapping("/task/{taskId}/download")
    @Operation(summary = "获取导出任务下载链接", description = "获取导出任务的下载链接")
    public ResponseEntity<Map<String, Object>> getExportTaskDownloadUrl(
            @Parameter(description = "任务ID") @PathVariable String taskId,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("获取导出任务下载链接: taskId={}, userId={}", taskId, userId);

        String downloadUrl = exportService.getExportTaskDownloadUrl(taskId);

        Map<String, Object> result = Map.of(
                "taskId", taskId,
                "downloadUrl", downloadUrl,
                "timestamp", System.currentTimeMillis());

        return ResponseEntity.ok(result);
    }

    /**
     * 取消导出任务
     *
     * @param taskId 任务ID
     * @param userId 用户ID
     * @return 取消结果
     */
    @PostMapping("/task/{taskId}/cancel")
    @Operation(summary = "取消导出任务", description = "取消指定的导出任务")
    public ResponseEntity<Map<String, Object>> cancelExportTask(
            @Parameter(description = "任务ID") @PathVariable String taskId,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("取消导出任务: taskId={}, userId={}", taskId, userId);

        exportService.cancelExportTask(taskId);

        Map<String, Object> result = Map.of(
                "taskId", taskId,
                "message", "导出任务取消成功",
                "timestamp", System.currentTimeMillis());

        return ResponseEntity.ok(result);
    }

    /**
     * 删除导出任务
     *
     * @param taskId 任务ID
     * @param userId 用户ID
     * @return 删除结果
     */
    @DeleteMapping("/task/{taskId}")
    @Operation(summary = "删除导出任务", description = "删除指定的导出任务")
    public ResponseEntity<Map<String, Object>> deleteExportTask(
            @Parameter(description = "任务ID") @PathVariable String taskId,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("删除导出任务: taskId={}, userId={}", taskId, userId);

        exportService.deleteExportTask(taskId);

        Map<String, Object> result = Map.of(
                "taskId", taskId,
                "message", "导出任务删除成功",
                "timestamp", System.currentTimeMillis());

        return ResponseEntity.ok(result);
    }

    /**
     * 获取用户导出任务列表
     *
     * @param userId 用户ID
     * @return 导出任务列表
     */
    @GetMapping("/user/tasks")
    @Operation(summary = "获取用户导出任务列表", description = "获取用户的所有导出任务")
    public ResponseEntity<List<ExportTask>> getUserExportTasks(
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("获取用户导出任务列表: userId={}", userId);

        List<ExportTask> tasks = exportService.getUserExportTasks(userId);
        return ResponseEntity.ok(tasks);
    }

    /**
     * 导出素材
     *
     * @param request 导出请求
     * @param userId  用户ID
     * @return 导出任务
     */
    @PostMapping("/materials")
    @Operation(summary = "导出素材", description = "导出用户的素材数据")
    public ResponseEntity<ExportTask> exportMaterials(
            @Valid @RequestBody Map<String, Object> request,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("导出素材: userId={}", userId);

        String format = (String) request.get("format");
        @SuppressWarnings("unchecked")
        Map<String, Object> filters = (Map<String, Object>) request.get("filters");
        @SuppressWarnings("unchecked")
        Map<String, Object> options = (Map<String, Object>) request.get("options");

        ExportTask task = exportService.exportMaterials(format, filters, options, userId);
        return ResponseEntity.ok(task);
    }

    /**
     * 导出文案
     *
     * @param request 导出请求
     * @param userId  用户ID
     * @return 导出任务
     */
    @PostMapping("/copywritings")
    @Operation(summary = "导出文案", description = "导出用户的文案数据")
    public ResponseEntity<ExportTask> exportCopywritings(
            @Valid @RequestBody Map<String, Object> request,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("导出文案: userId={}", userId);

        String format = (String) request.get("format");
        @SuppressWarnings("unchecked")
        Map<String, Object> filters = (Map<String, Object>) request.get("filters");
        @SuppressWarnings("unchecked")
        Map<String, Object> options = (Map<String, Object>) request.get("options");

        ExportTask task = exportService.exportCopywritings(format, filters, options, userId);
        return ResponseEntity.ok(task);
    }

    /**
     * 导出标签
     *
     * @param request 导出请求
     * @param userId  用户ID
     * @return 导出任务
     */
    @PostMapping("/tags")
    @Operation(summary = "导出标签", description = "导出用户的标签数据")
    public ResponseEntity<ExportTask> exportTags(
            @Valid @RequestBody Map<String, Object> request,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("导出标签: userId={}", userId);

        String format = (String) request.get("format");
        @SuppressWarnings("unchecked")
        Map<String, Object> filters = (Map<String, Object>) request.get("filters");
        @SuppressWarnings("unchecked")
        Map<String, Object> options = (Map<String, Object>) request.get("options");

        ExportTask task = exportService.exportTags(format, filters, options, userId);
        return ResponseEntity.ok(task);
    }

    /**
     * 导出统计数据
     *
     * @param request 导出请求
     * @param userId  用户ID
     * @return 导出任务
     */
    @PostMapping("/statistics")
    @Operation(summary = "导出统计数据", description = "导出统计数据")
    public ResponseEntity<ExportTask> exportStatistics(
            @Valid @RequestBody Map<String, Object> request,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("导出统计数据: userId={}", userId);

        String format = (String) request.get("format");
        @SuppressWarnings("unchecked")
        Map<String, Object> filters = (Map<String, Object>) request.get("filters");
        @SuppressWarnings("unchecked")
        Map<String, Object> options = (Map<String, Object>) request.get("options");

        ExportTask task = exportService.exportStatistics(format, filters, options, userId);
        return ResponseEntity.ok(task);
    }

    /**
     * 导出用户数据
     *
     * @param request 导出请求
     * @param userId  用户ID
     * @return 导出任务
     */
    @PostMapping("/user-data")
    @Operation(summary = "导出用户数据", description = "导出用户数据")
    public ResponseEntity<ExportTask> exportUserData(
            @Valid @RequestBody Map<String, Object> request,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("导出用户数据: userId={}", userId);

        String format = (String) request.get("format");
        @SuppressWarnings("unchecked")
        Map<String, Object> filters = (Map<String, Object>) request.get("filters");
        @SuppressWarnings("unchecked")
        Map<String, Object> options = (Map<String, Object>) request.get("options");

        ExportTask task = exportService.exportUserData(format, filters, options, userId);
        return ResponseEntity.ok(task);
    }

    /**
     * 批量导出
     *
     * @param request 批量导出请求
     * @param userId  用户ID
     * @return 导出任务列表
     */
    @PostMapping("/batch")
    @Operation(summary = "批量导出", description = "批量创建导出任务")
    public ResponseEntity<List<ExportTask>> batchExport(
            @Valid @RequestBody Map<String, Object> request,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("批量导出: userId={}", userId);

        @SuppressWarnings("unchecked")
        List<Map<String, Object>> exportRequests = (List<Map<String, Object>>) request.get("exports");

        List<ExportTask> tasks = exportService.batchExport(exportRequests, userId);
        return ResponseEntity.ok(tasks);
    }

    /**
     * 获取支持的导出格式
     *
     * @param dataType 数据类型
     * @return 支持的格式列表
     */
    @GetMapping("/formats")
    @Operation(summary = "获取支持的导出格式", description = "获取指定数据类型支持的导出格式")
    public ResponseEntity<List<String>> getSupportedExportFormats(
            @Parameter(description = "数据类型") @RequestParam(required = false) String dataType) {
        log.info("获取支持的导出格式: dataType={}", dataType);

        List<String> formats = exportService.getSupportedExportFormats(dataType);
        return ResponseEntity.ok(formats);
    }

    /**
     * 获取导出模板
     *
     * @param dataType 数据类型
     * @param format   格式
     * @return 模板列表
     */
    @GetMapping("/templates")
    @Operation(summary = "获取导出模板", description = "获取指定数据类型和格式的导出模板")
    public ResponseEntity<List<Map<String, Object>>> getExportTemplates(
            @Parameter(description = "数据类型") @RequestParam String dataType,
            @Parameter(description = "格式") @RequestParam String format) {
        log.info("获取导出模板: dataType={}, format={}", dataType, format);

        List<Map<String, Object>> templates = exportService.getExportTemplates(dataType, format);
        return ResponseEntity.ok(templates);
    }

    /**
     * 预览导出内容
     *
     * @param request 预览请求
     * @param userId  用户ID
     * @return 预览数据
     */
    @PostMapping("/preview")
    @Operation(summary = "预览导出内容", description = "预览导出内容")
    public ResponseEntity<Map<String, Object>> previewExportContent(
            @Valid @RequestBody Map<String, Object> request,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("预览导出内容: userId={}", userId);

        String dataType = (String) request.get("dataType");
        String format = (String) request.get("format");
        @SuppressWarnings("unchecked")
        Map<String, Object> filters = (Map<String, Object>) request.get("filters");
        @SuppressWarnings("unchecked")
        Map<String, Object> options = (Map<String, Object>) request.get("options");

        Map<String, Object> preview = exportService.previewExportContent(dataType, format, filters, options, userId);
        return ResponseEntity.ok(preview);
    }

    /**
     * 估算导出文件大小
     *
     * @param request 估算请求
     * @param userId  用户ID
     * @return 估算结果
     */
    @PostMapping("/estimate-size")
    @Operation(summary = "估算导出文件大小", description = "估算导出文件的大小")
    public ResponseEntity<Map<String, Object>> estimateExportFileSize(
            @Valid @RequestBody Map<String, Object> request,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("估算导出文件大小: userId={}", userId);

        String dataType = (String) request.get("dataType");
        String format = (String) request.get("format");
        @SuppressWarnings("unchecked")
        Map<String, Object> filters = (Map<String, Object>) request.get("filters");
        @SuppressWarnings("unchecked")
        Map<String, Object> options = (Map<String, Object>) request.get("options");

        Long estimatedSize = exportService.estimateExportFileSize(dataType, format, filters, options, userId);

        Map<String, Object> result = Map.of(
                "estimatedSize", estimatedSize,
                "unit", "bytes",
                "readableSize", formatFileSize(estimatedSize),
                "timestamp", System.currentTimeMillis());

        return ResponseEntity.ok(result);
    }

    /**
     * 清理过期导出文件
     *
     * @return 清理结果
     */
    @PostMapping("/cleanup")
    @Operation(summary = "清理过期导出文件", description = "清理过期的导出文件")
    public ResponseEntity<Map<String, Object>> cleanupExpiredExportFiles() {
        log.info("清理过期导出文件");

        int cleanedCount = exportService.cleanupExpiredExportFiles();

        Map<String, Object> result = Map.of(
                "cleanedCount", cleanedCount,
                "message", "过期导出文件清理完成",
                "timestamp", System.currentTimeMillis());

        return ResponseEntity.ok(result);
    }

    /**
     * 获取导出任务统计
     *
     * @param userId 用户ID
     * @return 统计信息
     */
    @GetMapping("/statistics")
    @Operation(summary = "获取导出任务统计", description = "获取导出任务的统计信息")
    public ResponseEntity<Map<String, Object>> getExportTaskStatistics(
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("获取导出任务统计: userId={}", userId);

        Map<String, Object> statistics = exportService.getExportTaskStatistics(userId);
        return ResponseEntity.ok(statistics);
    }

    /**
     * 重试导出任务
     *
     * @param taskId 任务ID
     * @param userId 用户ID
     * @return 重试结果
     */
    @PostMapping("/task/{taskId}/retry")
    @Operation(summary = "重试导出任务", description = "重试失败的导出任务")
    public ResponseEntity<Map<String, Object>> retryExportTask(
            @Parameter(description = "任务ID") @PathVariable String taskId,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("重试导出任务: taskId={}, userId={}", taskId, userId);

        exportService.retryExportTask(taskId);

        Map<String, Object> result = Map.of(
                "taskId", taskId,
                "message", "导出任务重试成功",
                "timestamp", System.currentTimeMillis());

        return ResponseEntity.ok(result);
    }

    /**
     * 设置导出任务优先级
     *
     * @param taskId  任务ID
     * @param request 优先级请求
     * @param userId  用户ID
     * @return 设置结果
     */
    @PostMapping("/task/{taskId}/priority")
    @Operation(summary = "设置导出任务优先级", description = "设置导出任务的优先级")
    public ResponseEntity<Map<String, Object>> setExportTaskPriority(
            @Parameter(description = "任务ID") @PathVariable String taskId,
            @Valid @RequestBody Map<String, Object> request,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("设置导出任务优先级: taskId={}, userId={}", taskId, userId);

        Integer priority = (Integer) request.get("priority");
        exportService.setExportTaskPriority(taskId, priority);

        Map<String, Object> result = Map.of(
                "taskId", taskId,
                "priority", priority,
                "message", "导出任务优先级设置成功",
                "timestamp", System.currentTimeMillis());

        return ResponseEntity.ok(result);
    }

    /**
     * 获取导出任务进度
     *
     * @param taskId 任务ID
     * @param userId 用户ID
     * @return 进度信息
     */
    @GetMapping("/task/{taskId}/progress")
    @Operation(summary = "获取导出任务进度", description = "获取导出任务的进度信息")
    public ResponseEntity<Map<String, Object>> getExportTaskProgress(
            @Parameter(description = "任务ID") @PathVariable String taskId,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("获取导出任务进度: taskId={}, userId={}", taskId, userId);

        Map<String, Object> progress = exportService.getExportTaskProgress(taskId);
        return ResponseEntity.ok(progress);
    }

    /**
     * 暂停导出任务
     *
     * @param taskId 任务ID
     * @param userId 用户ID
     * @return 暂停结果
     */
    @PostMapping("/task/{taskId}/pause")
    @Operation(summary = "暂停导出任务", description = "暂停正在执行的导出任务")
    public ResponseEntity<Map<String, Object>> pauseExportTask(
            @Parameter(description = "任务ID") @PathVariable String taskId,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("暂停导出任务: taskId={}, userId={}", taskId, userId);

        exportService.pauseExportTask(taskId);

        Map<String, Object> result = Map.of(
                "taskId", taskId,
                "message", "导出任务暂停成功",
                "timestamp", System.currentTimeMillis());

        return ResponseEntity.ok(result);
    }

    /**
     * 恢复导出任务
     *
     * @param taskId 任务ID
     * @param userId 用户ID
     * @return 恢复结果
     */
    @PostMapping("/task/{taskId}/resume")
    @Operation(summary = "恢复导出任务", description = "恢复暂停的导出任务")
    public ResponseEntity<Map<String, Object>> resumeExportTask(
            @Parameter(description = "任务ID") @PathVariable String taskId,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("恢复导出任务: taskId={}, userId={}", taskId, userId);

        exportService.resumeExportTask(taskId);

        Map<String, Object> result = Map.of(
                "taskId", taskId,
                "message", "导出任务恢复成功",
                "timestamp", System.currentTimeMillis());

        return ResponseEntity.ok(result);
    }

    /**
     * 批量删除导出任务
     *
     * @param taskIds 任务ID列表
     * @param userId  用户ID
     * @return 删除结果
     */
    @DeleteMapping("/task/batch")
    @Operation(summary = "批量删除导出任务", description = "批量删除导出任务")
    public ResponseEntity<Map<String, Object>> batchDeleteExportTasks(
            @Parameter(description = "任务ID列表") @RequestBody List<String> taskIds,
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("批量删除导出任务: taskIds={}, userId={}", taskIds, userId);

        exportService.batchDeleteExportTasks(taskIds);

        Map<String, Object> result = Map.of(
                "deletedCount", taskIds.size(),
                "message", "导出任务批量删除成功",
                "timestamp", System.currentTimeMillis());

        return ResponseEntity.ok(result);
    }

    /**
     * 获取导出配额使用情况
     *
     * @param userId 用户ID
     * @return 配额使用情况
     */
    @GetMapping("/quota/usage")
    @Operation(summary = "获取导出配额使用情况", description = "获取用户的导出配额使用情况")
    public ResponseEntity<Map<String, Object>> getExportQuotaUsage(
            @Parameter(description = "用户ID") @RequestHeader("X-User-Id") Long userId) {
        log.info("获取导出配额使用情况: userId={}", userId);

        Map<String, Object> quotaUsage = exportService.getExportQuotaUsage(userId);
        return ResponseEntity.ok(quotaUsage);
    }

    /**
     * 格式化文件大小
     *
     * @param size 文件大小（字节）
     * @return 可读的文件大小
     */
    private String formatFileSize(Long size) {
        if (size == null || size < 0) {
            return "0 B";
        }

        String[] units = { "B", "KB", "MB", "GB", "TB" };
        int unitIndex = 0;
        double fileSize = size.doubleValue();

        while (fileSize >= 1024 && unitIndex < units.length - 1) {
            fileSize /= 1024;
            unitIndex++;
        }

        return String.format("%.2f %s", fileSize, units[unitIndex]);
    }
}